<script setup lang="ts">
import { ref, defineProps, computed, watch, nextTick } from 'vue'

// 原生防抖函数实现
function debounce<T extends (...args: any[]) => any>(func: T, delay: number): T {
  let timeoutId: ReturnType<typeof setTimeout>
  return ((...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(this, args), delay)
  }) as T
}

// 完善类型定义
interface SelectItem {
  title: string
  value: any
  disabled?: boolean
}

interface SelectProps {
  key: string
  item: SelectItem[]
  placeholder?: string
}

interface TableHeader {
  key: string
  title: string
  align?: 'start' | 'center' | 'end'
  sortable?: boolean
  width?: string | number
  minWidth?: string | number
  maxWidth?: string | number
}

interface SearchParams {
  [key: string]: any
}

// 优化 props 类型定义
const props = withDefaults(defineProps<{
  cardTitle?: string
  tableHeaders: TableHeader[]
  tableData: any[]
  total?: number | null
  itemsPerPage?: number
  inputProps?: string[]
  selectProps?: SelectProps[]
  loading?: boolean
  showSearch?: boolean
  showActions?: boolean
}>(), {
  total: null,
  itemsPerPage: 10,
  loading: false,
  showSearch: true,
  showActions: true
})

// 完善事件定义
const emit = defineEmits<{
  search: [params: SearchParams]
  delete: [id: any]
  edit: [item: any]
  'page-change': [page: number]
  'items-per-page-change': [itemsPerPage: number]
}>()

// 响应式数据
const page = ref(1)
const inputValue = ref<Record<string, any>>({})
const selectValue = ref<Record<string, any>>({})
const searchLoading = ref(false)

// 计算属性优化
const pageCount = computed(() => {
  const totalCount = props.total !== null ? props.total : props.tableData.length
  return Math.ceil(totalCount / props.itemsPerPage)
})

const hasSearchFields = computed(() => {
  return (props.inputProps && props.inputProps.length > 0) || 
         (props.selectProps && props.selectProps.length > 0)
})

// 防抖搜索
const debouncedSearch = debounce(() => {
  performSearch()
}, 300)

// 搜索方法优化
async function search() {
  if (searchLoading.value) return
  debouncedSearch()
}

async function performSearch() {
  try {
    searchLoading.value = true
    const searchParams: SearchParams = {
      ...inputValue.value,
      ...selectValue.value
    }
    
    // 过滤空值
    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => 
        value !== null && value !== undefined && value !== ''
      )
    )
    
    emit('search', filteredParams)
    page.value = 1 // 搜索时重置页码
  } catch (error) {
    console.error('搜索出错:', error)
  } finally {
    searchLoading.value = false
  }
}

// 重置搜索
function resetSearch() {
  inputValue.value = {}
  selectValue.value = {}
  search()
}

// 删除操作优化
function handleDelete(item: any) {
  if (!item?.id) {
    console.warn('删除项缺少 ID')
    return
  }
  emit('delete', item.id)
}

// 编辑操作
function handleEdit(item: any) {
  emit('edit', item)
}

// 页码变化
function handlePageChange(newPage: number) {
  page.value = newPage
  emit('page-change', newPage)
}

// 监听页码变化
watch(page, (newPage) => {
  if (newPage !== page.value) {
    handlePageChange(newPage)
  }
})

// 初始化默认值
function initializeValues() {
  if (props.inputProps) {
    props.inputProps.forEach(key => {
      if (!(key in inputValue.value)) {
        inputValue.value[key] = ''
      }
    })
  }
  
  if (props.selectProps) {
    props.selectProps.forEach(item => {
      if (!(item.key in selectValue.value)) {
        selectValue.value[item.key] = null
      }
    })
  }
}

// 组件挂载时初始化
nextTick(() => {
  initializeValues()
})
</script>

<template>
  <div class="data-table-wrapper">
    <!-- 搜索卡片 -->
    <VCard 
      v-if="showSearch && hasSearchFields" 
      class="search-card" 
      elevation="1"
    >
      <VCardTitle class="search-card-title">
        <VIcon class="title-icon" color="primary">mdi-table-search</VIcon>
        {{ cardTitle || '数据查询' }}
        <VSpacer />
        <div class="title-actions">
          <slot name="actions"></slot>
        </div>
      </VCardTitle>
      
      <VCardText class="search-card-body">
        <VRow class="search-row" align="center">
          <!-- 输入框字段 -->
          <VCol 
            v-for="field in inputProps" 
            :key="field"
            cols="12" 
            sm="6" 
            md="4" 
            lg="3" 
            xl="2"
            class="field-col"
          >
            <VTextField 
              :label="field" 
              v-model="inputValue[field]" 
              clearable 
              variant="outlined" 
              density="comfortable"
              hide-details="auto"
              class="search-input"
              @keyup.enter="search"
            />
          </VCol>
          
          <!-- 选择框字段 -->
          <VCol 
            v-for="selectItem in selectProps" 
            :key="selectItem.key"
            cols="12" 
            sm="6" 
            md="4" 
            lg="3" 
            xl="2"
            class="field-col"
          >
            <VSelect 
              :items="selectItem.item" 
              :label="selectItem.key"
              :placeholder="selectItem.placeholder"
              v-model="selectValue[selectItem.key]" 
              clearable 
              variant="outlined" 
              density="comfortable"
              hide-details="auto"
              class="search-select"
              item-title="title"
              item-value="value"
            />
          </VCol>
          
          <!-- 操作按钮 -->
          <VCol 
            cols="12" 
            sm="6" 
            md="4" 
            lg="3" 
            xl="2"
            class="field-col actions-col"
          >
            <div class="button-group">
              <VBtn 
                @click="search" 
                color="primary"
                variant="elevated"
                prepend-icon="mdi-magnify"
                :loading="searchLoading"
                class="search-btn"
              >
                搜索
              </VBtn>
              <VBtn 
                @click="resetSearch"
                variant="outlined"
                color="secondary"
                prepend-icon="mdi-refresh"
                class="reset-btn"
              >
                重置
              </VBtn>
            </div>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- 表格部分 -->
    <VCard class="table-container" elevation="1">
      <VDataTable 
        class="data-table" 
        :headers="tableHeaders"
        :items="tableData"
        :items-per-page="itemsPerPage"
        v-model:page="page"
        :loading="loading"
        hover
        :height="600"
        fixed-header
        no-data-text="暂无数据"
        loading-text="正在加载..."
      >
        <!-- 透传所有插槽 -->
        <template v-for="(_, name) in $slots" :key="name" #[name]="slotProps">
          <slot :name="name" v-bind="slotProps || {}"></slot>
        </template>

        <!-- 默认操作列 --> 
        <template v-if="showActions && !$slots['item.actions']" #item.actions="{ item }">
          <div class="table-actions">
            <VBtn 
              icon="mdi-pencil" 
              variant="text" 
              color="info" 
              size="small" 
              title="编辑" 
              @click="handleEdit(item)"
            />
            <VBtn 
              icon="mdi-delete" 
              variant="text" 
              color="error" 
              size="small" 
              title="删除" 
              @click="handleDelete(item)"
            />
          </div>
        </template>

        <!-- 默认分页器 -->
        <template v-if="!$slots.bottom" #bottom>
          <div class="table-pagination">
            <VPagination
              v-model="page"
              :length="pageCount"
              :total-visible="5"
              rounded="circle"
              density="comfortable"
              show-first-last-page
            />
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>

<style scoped> 
.data-table-wrapper {
  width: 100%;
  margin: 0 auto;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  background: linear-gradient(145deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.search-card-title {
  font-weight: 600;
  font-size: 1.125rem;
  padding: 20px 24px 12px;
  display: flex;
  align-items: center;
  gap: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.title-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.title-icon {
  font-size: 1.3rem;
  color: #667eea;
}

.search-card-body {
  padding: 0 24px 20px;
}

.search-row {
  margin: 0 -8px;
}

.field-col {
  padding: 8px;
}

.search-input :deep(.v-field),
.search-select :deep(.v-field) {
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.12);
}

.search-input :deep(.v-field:hover),
.search-select :deep(.v-field:hover) {
  background: rgba(255, 255, 255, 1);
  border-color: rgba(102, 126, 234, 0.3);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.search-input :deep(.v-field--focused),
.search-select :deep(.v-field--focused) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.actions-col {
  display: flex;
  align-items: flex-end;
}

.button-group {
  display: flex;
  gap: 12px;
  width: 100%;
  flex-wrap: wrap;
}

.search-btn {
  flex: 1;
  min-width: 90px;
  border-radius: 10px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
  transform: translateY(-2px);
}

.reset-btn {
  flex: 1;
  min-width: 90px;
  border-radius: 10px;
  font-weight: 500;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  border-color: #cbd5e0;
  background: #f7fafc;
  transform: translateY(-1px);
}

.table-container {
  border-radius: 16px;
  overflow: hidden;
  border: none;
  background: linear-gradient(145deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  min-height: 650px;
  display: flex;
  flex-direction: column;
}

.data-table {
  flex: 1;
  background: transparent;
}

.data-table :deep(.v-data-table__wrapper) {
  height: 100%;
  overflow-y: auto;
  border-radius: 16px 16px 0 0;
}

.data-table :deep(table) {
  table-layout: fixed;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}

.data-table :deep(thead th) {
  background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
  color: #2d3748;
  font-weight: 700;
  font-size: 0.875rem;
  letter-spacing: 0.5px;
  text-transform: uppercase;
  border: none;
  border-bottom: 2px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 10;
  padding: 16px 20px;
  text-align: left;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.data-table :deep(thead th:first-child) {
  border-top-left-radius: 16px;
}

.data-table :deep(thead th:last-child) {
  border-top-right-radius: 16px;
}

.data-table :deep(tbody td) {
  padding: 16px 20px;
  border: none;
  border-bottom: 1px solid rgba(226, 232, 240, 0.6);
  background: #ffffff;
  font-size: 0.9rem;
  color: #4a5568;
  transition: all 0.2s ease;
}

.data-table :deep(tbody tr) {
  transition: all 0.2s ease;
  cursor: pointer;
}

.data-table :deep(tbody tr:nth-child(even) td) {
  background: rgba(248, 250, 252, 0.8);
}

.data-table :deep(tbody tr:hover td) {
  background: linear-gradient(135deg, #eef7ff 0%, #f0f9ff 100%);
  color: #1a202c;
  font-weight: 500;
  border-color: rgba(102, 126, 234, 0.2);
  transform: scale(1.001);
}

.data-table :deep(tbody tr:hover) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
  z-index: 1;
  position: relative;
}

.data-table :deep(.v-data-table-progress th) {
  height: 4px !important;
  padding: 0 !important;
  border: none !important;
}

.data-table :deep(.v-data-table-progress .v-progress-linear) {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  height: 4px;
  border-radius: 2px;
}

.table-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.table-actions :deep(.v-btn) {
  border-radius: 8px;
  transition: all 0.2s ease;
  min-width: 36px;
  height: 36px;
}

.table-actions :deep(.v-btn:hover) {
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.table-actions :deep(.v-btn--variant-text) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

.table-pagination {
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
  border-top: 1px solid rgba(226, 232, 240, 0.6);
  display: flex;
  justify-content: center;
  margin-top: auto;
  border-radius: 0 0 16px 16px;
}

.table-pagination :deep(.v-pagination .v-btn) {
  border-radius: 12px;
  margin: 0 3px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(226, 232, 240, 0.5);
}

.table-pagination :deep(.v-pagination .v-btn:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background: #ffffff;
  border-color: #cbd5e0;
}

.table-pagination :deep(.v-pagination .v-btn--active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  border: none;
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
  transform: translateY(-1px);
}

.table-pagination :deep(.v-pagination .v-btn--disabled) {
  opacity: 0.5;
  transform: none;
  box-shadow: none;
}

/* 加载状态美化 */
.data-table :deep(.v-data-table__empty-wrapper) {
  padding: 60px 20px;
  color: #718096;
  font-size: 1rem;
  font-weight: 500;
}

.data-table :deep(.v-skeleton-loader) {
  background: transparent;
}

.data-table :deep(.v-skeleton-loader__bone) {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 滚动条美化 */
.data-table :deep(.v-data-table__wrapper)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.data-table :deep(.v-data-table__wrapper)::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.data-table :deep(.v-data-table__wrapper)::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
  border-radius: 4px;
  transition: all 0.2s ease;
}

.data-table :deep(.v-data-table__wrapper)::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #a0aec0 0%, #718096 100%);
}

/* 响应式优化 */
@media (max-width: 600px) {
  .search-card {
    margin-bottom: 16px;
    border-radius: 8px;
  }

  .search-card-title {
    font-size: 1rem;
    padding: 16px 20px 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .title-actions {
    align-self: stretch;
    justify-content: flex-end;
  }
  
  .search-card-body {
    padding: 0 20px 16px;
  }
  
  .search-row {
    margin: 0 -6px;
  }
  
  .field-col {
    padding: 6px;
  }
  
  .button-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .table-container {
    min-height: 500px;
    border-radius: 12px;
  }
  
  .data-table :deep(.v-data-table__wrapper) {
    border-radius: 12px 12px 0 0;
  }
  
  .data-table :deep(thead th) {
    padding: 12px 16px;
    font-size: 0.8rem;
  }

  .data-table :deep(tbody td) {
    padding: 12px 16px;
    font-size: 0.85rem;
  }
  
  .table-actions {
    flex-direction: column;
    gap: 4px;
  }

  .table-actions :deep(.v-btn) {
    min-width: 32px;
    height: 32px;
  }
  
  .table-pagination {
    padding: 16px 12px;
    border-radius: 0 0 12px 12px;
  }
  
  .table-pagination :deep(.v-pagination) {
    --v-pagination-item-size: 32px;
  }

  .table-pagination :deep(.v-pagination .v-btn) {
    border-radius: 8px;
    margin: 0 2px;
  }
}

@media (max-width: 400px) {
  .search-card-title {
    padding: 12px 16px 8px;
  }
  
  .search-card-body {
    padding: 0 16px 12px;
  }
  
  .button-group .v-btn {
    height: 36px;
    font-size: 0.875rem;
  }
  
  .data-table :deep(thead th) {
    padding: 10px 12px;
  }

  .data-table :deep(tbody td) {
    padding: 10px 12px;
    font-size: 0.8rem;
  }
}

/* 打印样式 */
@media print {
  .search-card,
  .table-pagination {
    display: none !important;
  }
  
  .table-container {
    box-shadow: none !important;
    border: 1px solid #000 !important;
    border-radius: 0 !important;
  }
  
  .data-table :deep(table) {
    font-size: 11px;
  }

  .data-table :deep(thead th) {
    background: #f5f5f5 !important;
    color: #000 !important;
  }

  .data-table :deep(tbody td) {
    background: #fff !important;
    color: #000 !important;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .search-card {
    background: linear-gradient(145deg, #1a202c 0%, #2d3748 100%);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .table-container {
    background: linear-gradient(145deg, #1a202c 0%, #2d3748 100%);
  }

  .data-table :deep(thead th) {
    background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
    color: #e2e8f0;
  }

  .data-table :deep(tbody td) {
    background: #1a202c;
    color: #e2e8f0;
    border-color: rgba(255, 255, 255, 0.1);
  }

  .data-table :deep(tbody tr:nth-child(even) td) {
    background: rgba(45, 55, 72, 0.5);
  }

  .data-table :deep(tbody tr:hover td) {
    background: linear-gradient(135deg, #2b6cb0 0%, #3182ce 100%);
  }

  .table-pagination {
    background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
    border-color: rgba(255, 255, 255, 0.1);
  }
}
</style>